#!/usr/bin/python3

from xml.dom.minidom import parse
import xml.dom.minidom
import sys
from typing import List, Optional

def validate_args():
    """Validate command line arguments."""
    if len(sys.argv) != 3:
        print("Usage: {} <output_file> <package_xml>".format(sys.argv[0]))
        sys.exit(1)

def parse_package_xml(xml_file: str) -> xml.dom.minidom.Document:
    """Parse package.xml file and return document element."""
    try:
        return xml.dom.minidom.parse(xml_file)
    except Exception as e:
        print(f"Error parsing XML file: {e}")
        sys.exit(1)

def write_to_file(filename: str, content: str, mode: str = 'a+'):
    """Write content to file with error handling."""
    try:
        with open(filename, mode, encoding='utf-8') as f:
            f.write(content + "\n")
    except IOError as e:
        print(f"Error writing to file {filename}: {e}")
        sys.exit(1)

def should_skip_dependency(dep: xml.dom.minidom.Element) -> bool:
    """Check if dependency should be skipped based on conditions."""
    if dep.hasAttribute("ROS_VERSION") and dep.getAttribute("ROS_VERSION") == "1":
        return True
    
    if dep.hasAttribute("condition"):
        condition = dep.getAttribute("condition")
        if condition in ["$ROS_VERSION == 1", "$ROS_PYTHON_VERSION == 2"]:
            return True
    
    if dep.hasAttribute("type"):
        return dep.getAttribute("type") != "website"
    
    return False

def get_depend(depend_name: str, org_depend_file_name: str):
    """Extract and write dependency information from package.xml."""
    deps = collection.getElementsByTagName(depend_name)
    
    # Handle description separately
    if depend_name == "description":
        if len(deps) > 0:
            write_to_file(org_depend_file_name, deps[0].childNodes[0].data, 'w')
        return

    for dep in deps:
        if should_skip_dependency(dep):
            continue
        
        child_node = dep.childNodes[0].data if len(dep.childNodes) > 0 else ""
        
        if depend_name == "maintainer" and dep.hasAttribute("email"):
            content = f"{depend_name}:{child_node} {dep.getAttribute('email')}"
            write_to_file(org_depend_file_name, content)
            return
        
        content = child_node if depend_name == "description" else f"{depend_name}:{child_node}"
        write_to_file(org_depend_file_name, content)

def main():
    validate_args()
    global collection
    collection = parse_package_xml(sys.argv[2]).documentElement
    
    # Process all dependency types
    dependencies = [
        "name", "depend", "build_depend", "build_export_depend",
        "exec_depend", "test_depend", "buildtool_depend",
        "buildtool_export_depend", "run_depend", "license",
        "url", "maintainer"
    ]
    
    for dep in dependencies:
        get_depend(dep, sys.argv[1])
    
    # Handle description separately
    get_depend("description", sys.argv[1] + "-description")

if __name__ == "__main__":
    main()
